<script setup lang="ts">
import {
  inventoryPlanList,
  addinventoryPlan,
  delinventoryPlan,
  updateinventoryPlan,
  ForminventoryPlan,
  LibraryOptions,
  inventoryRouteOptions,
  inventoryTimeOptions,
} from "@/api/InvPlan/index.ts";
import { ElMessage, ElMessageBox } from "element-plus";
import type { RequestParams, Data } from "@/api/InvPlan/type";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
import { onMounted, reactive, ref } from "vue";
const RobotList = ref([] as Data[]); //列表数据

const InvTime = ref();
const routeOptList = ref();
const libraryaOpt = ref();
const libOptions = async () => {
  const { data } = await LibraryOptions(useStore.encryptedData);
  libraryaOpt.value = data;
  //console.log(data, "图书馆");
};
const ids = ref([]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
const ruleFormRef = ref(); //弹框表单
const ruleForm = ref({} as any);
const rowId = ref();
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
} as RequestParams);
const rules = reactive({
  libraryId: [{ required: true, message: "请选择图书馆", trigger: "change" }],
  routeId: [{ required: true, message: "请选择盘点路线", trigger: "change" }],
  timeId: [{ required: true, message: "请选择盘点时间", trigger: "change" }],
  typeId: [{ required: true, message: "请选择盘点类型", trigger: "change" }],

  planName: [
    { required: true, message: "盘点计划名称不能为空", trigger: "blur" },
    { min: 1, max: 20, message: "盘点计划名称过长", trigger: "blur" },
  ],
});
/**
 * 列表数据
 */
const centerDialogVisible = ref(false);
const getRbtList = async () => {
  try {
    const res = await inventoryPlanList(queryParams.value);
    RobotList.value = res.data.records;
    total.value = res.data.total;
    // console.log(res, "分页列表1");
    // console.log(queryParams.value);
  } catch (error) {
    console.error(error);
  }
};
const librowID = ref();
const timeIdRef = ref();
const routeIdItem = ref();
const changeLib = async (e: any) => {
  title.value = "新增";
  ruleForm.value.timeId = "";
  ruleForm.value.routeId = "";
  librowID.value = e;
  // -----------------------
  const res = await inventoryTimeOptions(e);
  InvTime.value = res.data;
  //console.log(res, "时间盘点");
  timeIdRef.value.clearValidate();
  // -----------------------
  const { data } = await inventoryRouteOptions(e);
  routeOptList.value = data;
  //console.log(data, "路线下拉");
  routeIdItem.value.clearValidate();
};

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */

const openDialog = () => {
  title.value = "新增";
  dialogVisible.value = true;
};
/**
 * 关闭弹框
 */
const close = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
  ruleForm.value = {} as any;
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  try {
    // 表示当前页面正在异步处理中
    loading.value = true;
    // 验证表单数据是否合法
    const isValid = await ruleFormRef.value.validate();
    if (isValid) {
      //   console.log(ruleForm.value, "ruleForm.value");
      // 提交数据到服务器
      if (title.value === "新增") {
        const res = await addinventoryPlan(ruleForm.value);
        if (res.code === 200) {
          ElMessage.success("新增成功");
          // 关闭对话框并重新查询列表数据
          close();
          getRbtList();
          loading.value = false;
        } else {
          ElMessage.error(res.msg);
          loading.value = false;
        }
      } else {
        const res = await updateinventoryPlan(ruleForm.value);
        if (res.code === 200) {
          ElMessage.success("修改成功");
          // 关闭对话框并重新查询列表数据
          close();
          getRbtList();
          loading.value = false;
        }
      }
    }
  } catch (error) {
    console.error(error);
    // 在发生异常时，取消页面加载状态
    loading.value = false;
  }
};
/**
 * 编辑
 */
const edit = async (row: any) => {
  dialogVisible.value = true;
  title.value = "编辑";
  rowId.value = row.id;
  if ((title.value = "编辑")) {
    const { data } = await ForminventoryPlan(row.id);
    ruleForm.value = data;
    //console.log(data);
    const res = await inventoryTimeOptions(data.libraryId);
    InvTime.value = res.data;
    //console.log(res, "时间盘点");

    // -----------------------
    const ress = await inventoryRouteOptions(data.libraryId);
    routeOptList.value = ress.data;
  }
};
/**
 * 删除
 */
const dell = (row: any) => {
  const userIds = [row.id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async function () {
    const res = await delinventoryPlan(row.id);
    //console.log(res, "删除");

    if (res.code == 200) {
      getRbtList();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("删除失败");
    }
  });
};

onMounted(() => {
  getRbtList();

  libOptions();
  //RouteOptions();
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getRbtList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getRbtList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
const ruForm = ref({} as any);
const details = async (row: any) => {
  const { data } = await ForminventoryPlan(row.id);

  ruForm.value = data;
  const res = await inventoryTimeOptions(data.libraryId);
  InvTime.value = res.data;
  //console.log(res, "时间盘点");

  // -----------------------
  const ress = await inventoryRouteOptions(data.libraryId);
  routeOptList.value = ress.data;
  centerDialogVisible.value = true;
};
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
</script>

<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <el-button type="success" @click="openDialog">新增</el-button>
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="RobotList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <!--  <el-table-column type="selection" width="55" align="center" /> > -->
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <el-table-column label="任务名称" prop="planName" :align="'center'" />
        <el-table-column label="盘点路线" prop="routeName" :align="'center'" />
        <el-table-column label="开始时间" prop="startTime" :align="'center'" />
        <el-table-column label="预约人" prop="creatorName" :align="'center'" />
        <el-table-column
          fixed="right"
          label="操作"
          :align="'center'"
          width="220"
        >
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="edit(row)"
              >编辑</el-button
            >
            <el-button type="primary" link size="small" @click="dell(row)"
              >删除</el-button
            >
            <el-button type="primary" link size="small" @click="details(row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="550px"
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="95px"
        status-icon
      >
        <el-form-item
          label="图书馆"
          prop="libraryId"
          style="white-space: nowrap"
        >
          <el-select
            v-model="ruleForm.libraryId"
            placeholder="请选择图书馆"
            @change="changeLib"
          >
            <el-option
              v-for="item in libraryaOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          ref="routeIdItem"
          label="盘点路线"
          prop="routeId"
          style="white-space: nowrap"
        >
          <el-select v-model="ruleForm.routeId" placeholder="请选择盘点路线">
            <el-option
              v-for="item in routeOptList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          ref="timeIdRef"
          label="盘点时间"
          prop="timeId"
          style="white-space: nowrap"
        >
          <el-select v-model="ruleForm.timeId" placeholder="请选择盘点时间">
            <el-option
              v-for="item in InvTime"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="预约盘点名称"
          prop="planName"
          style="white-space: nowrap"
        >
          <el-input v-model="ruleForm.planName" placeholder="预约盘点名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog
      v-model="centerDialogVisible"
      title="预约盘点详情"
      width="35%"
      align-center
    >
      <el-form :model="ruForm" label-width="95px" status-icon>
        <el-form-item
          label="图书馆"
          prop="libraryId"
          style="white-space: nowrap"
        >
          <el-select
            disabled
            v-model="ruForm.libraryId"
            placeholder="请选择图书馆"
            @change="changeLib"
          >
            <el-option
              v-for="item in libraryaOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          ref="routeIdItem"
          label="盘点路线"
          prop="routeId"
          style="white-space: nowrap"
        >
          <el-select
            v-model="ruForm.routeId"
            placeholder="请选择盘点路线"
            disabled
          >
            <el-option
              v-for="item in routeOptList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          ref="timeIdRef"
          label="盘点时间"
          prop="timeId"
          style="white-space: nowrap"
        >
          <el-select
            v-model="ruForm.timeId"
            placeholder="请选择盘点时间"
            disabled
          >
            <el-option
              v-for="item in InvTime"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="预约盘点名称"
          prop="planName"
          style="white-space: nowrap"
        >
          <el-input
            v-model="ruForm.planName"
            placeholder="预约盘点名称"
            disabled
          />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
